<?php
namespace App\Task;

use App\Storage\ChatMessageFile;
use App\Storage\OnlineUser;
use App\Storage\OnlineShop;
use App\WebSocket\WebSocketAction;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Swoole\Task\AbstractAsyncTask;

class BroadcastTask extends AbstractAsyncTask {


    protected function run($taskData, $taskId, $fromWorkerId, $flags = null)
    {
        // TODO: Implement run() method.
        $server = ServerManager::getInstance()->getSwooleServer();

        $shopId = empty($taskData['shopId']) ? 0 : intval($taskData['shopId']) ;
        if ($shopId && $shopId > 0) {
            foreach (OnlineUser::getInstance()->table() as $userFd => $userInfo) { // 房间内广播
                if ($userInfo['shop_id'] == $shopId) {
                    $connection = $server->connection_info($userFd);
                    if ($connection['websocket_status'] == 3) { // 用户在线时可以正常进行消息推送
                        $server->push($userInfo['fd'], $taskData['payload']);
                    }
                }
            }
        } else {
            foreach (OnlineUser::getInstance()->table() as $userFd => $userInfo) { // 全员广播
                $connection = $server->connection_info($userFd);
                if ($connection['websocket_status'] == 3) { // 用户在线时可以正常进行消息推送
                    $server->push($userInfo['fd'], $taskData['payload']);
                }
            }
        }

        // 添加到离线消息
        $payload = json_decode($taskData['payload'], true);
        if ($payload['action'] == 103) {
            $userInfo = OnlineUser::getInstance()->get($taskData['fromFd']);
            $payload['fromUserFd'] = 0;
            $payload['action'] = WebSocketAction::BROADCAST_LAST_MESSAGE;
            $payload['username'] = $userInfo['username'];
            $payload['avatar'] = $userInfo['avatar'];
            $payload['shopId'] = $userInfo['shop_id'];
            ChatMessageFile::getInstance()->saveMessage(json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        }

        return true;
    }

    protected function finish($result, $task_id)
    {
        // TODO: Implement finish() method.
    }
}